{% extends "base.html" %}

{% block title %}首页 - 视频生成系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="jumbotron bg-primary text-white rounded p-5 mb-4">
            <h1 class="display-4">
                <i class="fas fa-video me-3"></i>
                视频生成系统
            </h1>
            <p class="lead">
                将Markdown文档转换为专业的教学视频，支持代码高亮、数学公式、主题定制等功能
            </p>
            <hr class="my-4 bg-white">
            <p class="mb-0">
                <i class="fas fa-check-circle me-2"></i>
                简单易用 •
                <i class="fas fa-check-circle me-2"></i>
                高质量输出 •
                <i class="fas fa-check-circle me-2"></i>
                完全免费
            </p>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-upload me-2 text-primary"></i>
                    上传Markdown文件
                </h5>
                <p class="card-text">
                    选择一个或多个Markdown文件开始生成视频
                </p>
                <form id="uploadForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <input type="file" class="form-control" id="fileInput" name="file" accept=".md" required>
                        <div class="form-text">仅支持 .md 格式文件</div>
                    </div>
                    <button type="submit" class="btn btn-primary" id="uploadBtn">
                        <i class="fas fa-cloud-upload-alt me-2"></i>
                        上传文件
                    </button>
                </form>
                <div id="uploadResult" class="mt-3" style="display: none;"></div>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-cog me-2 text-primary"></i>
                    生成配置
                </h5>
                <form id="configForm">
                    <div class="mb-3">
                        <label for="quality" class="form-label">质量级别</label>
                        <select class="form-select" id="quality" name="quality">
                            <option value="preview">预览 (快速)</option>
                            <option value="standard" selected>标准 (推荐)</option>
                            <option value="high">高质量 (较慢)</option>
                            <option value="ultra">最高质量 (很慢)</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="theme" class="form-label">主题风格</label>
                        <select class="form-select" id="theme" name="theme">
                            <option value="dark" selected>深色主题</option>
                            <option value="light">浅色主题</option>
                            <option value="academic">学术风格</option>
                            <option value="presentation">演示风格</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="resolution" class="form-label">分辨率</label>
                        <select class="form-select" id="resolution" name="resolution">
                            <option value="1280x720">720p (1280x720)</option>
                            <option value="1920x1080" selected>1080p (1920x1080)</option>
                            <option value="2560x1440">1440p (2560x1440)</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="fps" class="form-label">帧率</label>
                        <select class="form-select" id="fps" name="fps">
                            <option value="24">24 fps</option>
                            <option value="30" selected>30 fps</option>
                            <option value="60">60 fps</option>
                        </select>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-play me-2 text-primary"></i>
                    开始生成
                </h5>
                <p class="card-text">
                    配置完成后点击开始生成按钮
                </p>
                <button class="btn btn-success btn-lg w-100" id="generateBtn" disabled>
                    <i class="fas fa-video me-2"></i>
                    开始生成视频
                </button>
            </div>
        </div>

        <div class="card" id="progressCard" style="display: none;">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-tasks me-2 text-primary"></i>
                    生成进度
                </h5>
                <div id="taskId" class="text-muted small mb-2"></div>
                <div class="progress mb-3" style="height: 30px;">
                    <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated"
                         role="progressbar" style="width: 0%">
                        <span id="progressText">0%</span>
                    </div>
                </div>
                <div id="currentStep" class="text-center text-muted mb-2"></div>
                <div id="logOutput" class="bg-dark text-light p-3 rounded" style="max-height: 300px; overflow-y: auto; font-size: 0.9em;">
                    <div class="small">等待开始...</div>
                </div>
            </div>
        </div>

        <div class="card" id="resultCard" style="display: none;">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-check-circle me-2 text-success"></i>
                    生成完成
                </h5>
                <div id="resultMessage" class="alert alert-success"></div>
                <a id="downloadBtn" href="#" class="btn btn-primary" download>
                    <i class="fas fa-download me-2"></i>
                    下载视频
                </a>
            </div>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-12">
        <h3>
            <i class="fas fa-list me-2"></i>
            任务列表
        </h3>
        <div id="taskList">
            <div class="text-muted">暂无任务</div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let socket = io();
let currentTaskId = null;
let uploadTaskId = null;

// 上传文件
document.getElementById('uploadForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData();
    const file = document.getElementById('fileInput').files[0];
    if (!file) return;

    formData.append('file', file);

    const uploadBtn = document.getElementById('uploadBtn');
    uploadBtn.disabled = true;
    uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>上传中...';

    fetch('/api/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.task_id) {
            uploadTaskId = data.task_id;
            showUploadResult(data);
            document.getElementById('generateBtn').disabled = false;
        } else {
            showError(data.error || '上传失败');
        }
    })
    .catch(error => {
        showError('上传失败: ' + error.message);
    })
    .finally(() => {
        uploadBtn.disabled = false;
        uploadBtn.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>上传文件';
    });
});

// 显示上传结果
function showUploadResult(data) {
    const result = document.getElementById('uploadResult');
    result.style.display = 'block';
    result.className = 'alert alert-success';
    result.innerHTML = `
        <i class="fas fa-check-circle me-2"></i>
        上传成功: ${data.filename}
    `;
}

// 开始生成
document.getElementById('generateBtn').addEventListener('click', function() {
    if (!uploadTaskId) {
        showError('请先上传文件');
        return;
    }

    const config = {
        task_id: uploadTaskId,
        quality: document.getElementById('quality').value,
        theme: document.getElementById('theme').value,
        resolution: document.getElementById('resolution').value,
        fps: document.getElementById('fps').value
    };

    const generateBtn = document.getElementById('generateBtn');
    generateBtn.disabled = true;
    generateBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>生成中...';

    fetch('/api/generate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(config)
    })
    .then(response => response.json())
    .then(data => {
        if (data.task_id) {
            currentTaskId = data.task_id;
            showProgress(data.task_id);
            connectToTask(data.task_id);
        } else {
            showError(data.error || '生成失败');
            generateBtn.disabled = false;
            generateBtn.innerHTML = '<i class="fas fa-video me-2"></i>开始生成视频';
        }
    })
    .catch(error => {
        showError('生成失败: ' + error.message);
        generateBtn.disabled = false;
        generateBtn.innerHTML = '<i class="fas fa-video me-2"></i>开始生成视频';
    });
});

// 显示进度
function showProgress(taskId) {
    document.getElementById('progressCard').style.display = 'block';
    document.getElementById('taskId').textContent = `任务ID: ${taskId}`;
    document.getElementById('logOutput').innerHTML = '<div class="small">开始处理...</div>';

    // 滚动到底部
    document.getElementById('logOutput').scrollTop = document.getElementById('logOutput').scrollHeight;
}

// 连接到任务
function connectToTask(taskId) {
    socket.emit('check_status', {task_id: taskId});
}

// 监听进度更新
socket.on('progress', function(data) {
    if (data.task_id === currentTaskId) {
        updateProgress(data.progress, data.status);
    }
});

// 监听完成
socket.on('completed', function(data) {
    if (data.task_id === currentTaskId) {
        updateProgress(100, '完成');
        showResult(data.task_id);

        // 重置按钮
        document.getElementById('generateBtn').disabled = false;
        document.getElementById('generateBtn').innerHTML = '<i class="fas fa-video me-2"></i>开始生成视频';
    }
});

// 监听错误
socket.on('error', function(data) {
    if (data.task_id === currentTaskId) {
        showError('生成失败: ' + data.error);

        // 重置按钮
        document.getElementById('generateBtn').disabled = false;
        document.getElementById('generateBtn').innerHTML = '<i class="fas fa-video me-2"></i>开始生成视频';
    }
});

// 更新进度
function updateProgress(progress, status) {
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const currentStep = document.getElementById('currentStep');
    const logOutput = document.getElementById('logOutput');

    progressBar.style.width = progress + '%';
    progressText.textContent = progress + '%';
    currentStep.textContent = status;

    // 添加日志
    const time = new Date().toLocaleTimeString();
    const logEntry = document.createElement('div');
    logEntry.className = 'small';
    logEntry.innerHTML = `<span class="text-muted">[${time}]</span> ${status}`;
    logOutput.appendChild(logEntry);

    // 滚动到底部
    logOutput.scrollTop = logOutput.scrollHeight;
}

// 显示结果
function showResult(taskId) {
    const resultCard = document.getElementById('resultCard');
    const resultMessage = document.getElementById('resultMessage');
    const downloadBtn = document.getElementById('downloadBtn');

    resultMessage.innerHTML = '<i class="fas fa-check-circle me-2"></i>视频生成完成！';
    downloadBtn.href = `/api/download/${taskId}`;

    resultCard.style.display = 'block';
}

// 错误提示
function showError(message) {
    const result = document.getElementById('uploadResult');
    result.style.display = 'block';
    result.className = 'alert alert-danger';
    result.innerHTML = `<i class="fas fa-exclamation-circle me-2"></i>${message}`;
}

// 页面加载时获取任务列表
window.addEventListener('load', function() {
    fetchTasks();
    // 每30秒刷新一次任务列表
    setInterval(fetchTasks, 30000);
});

// 获取任务列表
function fetchTasks() {
    fetch('/api/tasks')
    .then(response => response.json())
    .then(data => {
        updateTaskList(data.tasks || []);
    })
    .catch(error => {
        console.error('获取任务列表失败:', error);
    });
}

// 更新任务列表
function updateTaskList(tasks) {
    const taskList = document.getElementById('taskList');

    if (tasks.length === 0) {
        taskList.innerHTML = '<div class="text-muted">暂无任务</div>';
        return;
    }

    let html = '<div class="table-responsive">';
    html += '<table class="table table-hover">';
    html += '<thead><tr><th>任务ID</th><th>文件名</th><th>状态</th><th>进度</th><th>开始时间</th></tr></thead>';
    html += '<tbody>';

    tasks.forEach(task => {
        const statusBadge = getStatusBadge(task.status);
        const progress = task.progress || 0;

        html += '<tr>';
        html += `<td><code>${task.task_id.substring(0, 8)}...</code></td>`;
        html += `<td>${task.file}</td>`;
        html += `<td>${statusBadge}</td>`;
        html += `<td>
            <div class="progress" style="height: 20px;">
                <div class="progress-bar" style="width: ${progress}%">${progress}%</div>
            </div>
        </td>`;
        html += `<td>${formatTime(task.start_time)}</td>`;
        html += '</tr>';
    });

    html += '</tbody></table></div>';
    taskList.innerHTML = html;
}

// 获取状态徽章
function getStatusBadge(status) {
    const badges = {
        'processing': '<span class="badge bg-primary">处理中</span>',
        'completed': '<span class="badge bg-success">已完成</span>',
        'failed': '<span class="badge bg-danger">失败</span>',
        'pending': '<span class="badge bg-warning">等待中</span>'
    };
    return badges[status] || '<span class="badge bg-secondary">未知</span>';
}

// 格式化时间
function formatTime(timeStr) {
    if (!timeStr) return '-';
    const date = new Date(timeStr);
    return date.toLocaleString();
}
</script>
{% endblock %}
